import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const routes = [
  {
    path: '/',
    redirect: '/login',
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('@/views/auth/Login.vue'),
    meta: { requiresAuth: false, title: '登录' }
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('@/views/auth/Register.vue'),
    meta: { requiresAuth: false, title: '注册' }
  },
  {
    path: '/forgot-password',
    name: 'ForgotPassword',
    component: () => import('@/views/auth/ForgotPassword.vue'),
    meta: { requiresAuth: false, title: '忘记密码' }
  },
 
  {
    path: '/home',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: 'profile',
        name: 'UserProfile',
        component: () => import('@/views/profile/UserProfile.vue'),
        meta: { 
          title: '个人资料',
          hideInMenu: true
        }
      },
      {
        path: '',
        name: 'Dashboard',
        component: () => import('@/views/dashboard/Dashboard.vue'),
        meta: { 
          title: '仪表盘',
          icon: 'Dashboard'
        }
      },
      {
        path: 'dashboard-real',
        name: 'DashboardReal',
        component: () => import('@/views/dashboard/RealDataDashboard.vue'),
        meta: { 
          title: '实时数据仪表盘',
          icon: 'Monitor',
          hideInMenu: true
        }
      },
      {
        path: 'analytics',
        name: 'Analytics',
        component: () => import('@/views/analytics/Analytics.vue'),
        meta: { 
          title: '分析页',
          icon: 'TrendCharts',
          permission: 'analytics.dashboard'
        }
      },
      {
        path: 'monitoring',
        name: 'Monitoring',
        component: () => import('@/views/monitoring/Monitoring.vue'),
        meta: { 
          title: '监控页',
          icon: 'Monitor',
          permission: 'monitoring.system'
        }
      },
      {
        path: 'template-center',
        component: () => import('@/views/template/TemplateCenter.vue'),
        meta: { 
          title: '模板中心',
          icon: 'Grid',
          permission: 'template.view'
        },
        redirect: '/home/template-center/templates',
        children: [
          {
            path: 'templates',
            name: 'TemplateList',
            component: () => import('@/views/template/TemplateList.vue'),
            meta: { 
              title: '模板案例',
              icon: 'Collection'
            }
          },
          {
            path: 'create',
            name: 'CreateTemplate',
            component: () => import('@/views/template/CreateTemplate.vue'),
            meta: { 
              title: '创建模板',
              icon: 'Plus'
            }
          }
        ]
      },
      {
        path: 'component-center',
        name: 'ComponentCenter', 
        component: () => import('@/views/component/ComponentCenter.vue'),
        meta: { 
          title: '组件中心',
          icon: 'Histogram'
        },
        redirect: '/home/component-center/basic',
        children: [
          {
            path: 'basic',
            name: 'BasicComponents',
            component: () => import('@/views/component/BasicComponents.vue'),
            meta: { 
              title: '基本组件',
              icon: 'Grid'
            }
          },
          {
            path: 'icons',
            name: 'IconComponents',
            component: () => import('@/views/component/IconComponents.vue'),
            meta: { 
              title: '图标组件',
              icon: 'Star'
            }
          },
          {
            path: 'charts',
            name: 'ChartComponents',
            component: () => import('@/views/component/ChartComponents.vue'),
            meta: { 
              title: '图形组件',
              icon: 'TrendCharts'
            }
          }
        ]
      },
      {
        path: 'users',
        name: 'UserManagement',
        component: () => import('@/views/users/UserList.vue'),
        meta: { 
          title: '用户管理',
          icon: 'User',
          permission: 'user.view'
        }
      },
      {
        path: 'roles',
        name: 'RoleManagement',
        component: () => import('@/views/roles/RoleList.vue'),
        meta: { 
          title: '角色管理',
          icon: 'UserFilled',
          permission: 'role.view'
        }
      },
      {
        path: 'permissions',
        name: 'PermissionManagement',
        component: () => import('@/views/permissions/index.vue'),
        meta: { 
          title: '权限管理',
          icon: 'Key',
          permission: 'permission.view'
        }
      },
      {
        path: 'menus',
        name: 'MenuManagement',
        component: () => import('@/views/menus/MenuList.vue'),
        meta: { 
          title: '菜单管理',
          icon: 'Menu',
          permission: 'menu.view'
        }
      },
      {
        path: 'settings',
        name: 'SystemSettings',
        component: () => import('@/views/settings/index.vue'),
        meta: { 
          title: '系统设置',
          icon: 'Setting',
          permission: 'system.settings'
        }
      },
      {
        path: 'logs',
        name: 'LogCenter',
        component: () => import('@/views/logs/LogCenter.vue'),
        meta: { 
          title: '日志中心',
          icon: 'Document',
          permission: 'log.view'
        }
      },
      {
        path: 'debug-permissions',
        name: 'DebugPermissions',
        component: () => import('@/views/debug/PermissionTest.vue'),
        meta: { 
          title: '权限调试',
          icon: 'Tools'
        }
      }
    ]
  },
  {
    path: '/403',
    name: 'Forbidden',
    component: () => import('@/views/error/403.vue'),
    meta: { requiresAuth: false, title: '访问被拒绝' }
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/error/404.vue')
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 通用管理系统`
  }

  // 处理根路径访问：如果已登录则重定向到首页，否则重定向到登录页
  if (to.path === '/') {
    if (userStore.token) {
      next('/home')
    } else {
      next('/login')
    }
    return
  }

  // 检查是否需要登录
  if (to.meta.requiresAuth !== false) {
    if (!userStore.token) {
      next('/login')
      return
    }

    // 检查权限
    if (to.meta.permission && !userStore.hasPermission(to.meta.permission)) {
      next('/403')
      return
    }
  }

  // 如果已登录访问登录页面，重定向到仪表盘
  if (to.path === '/login' && userStore.token) {
    next('/home')
    return
  }

  next()
})

export default router
